
#include "stdafx.h"
#include "Gps.h"

Gps::Gps() {
	gps_h = NULL;
	g_hGPSEvents[0] = NULL;
	g_hGPSEvents[1] = NULL;
}

Gps::~Gps() {
	if (gps_h) 
		GPSCloseDevice(gps_h);

	gps_h = NULL;
	g_hGPSEvents[0] = NULL;
	g_hGPSEvents[1] = NULL;
}

bool Gps::openDevice() {
	if (!gps_h) {
		g_hGPSEvents[0] = CreateEvent(NULL,true,false,NULL);
		g_hGPSEvents[1] = CreateEvent(NULL,true,false,NULL);
		gps_h=GPSOpenDevice(g_hGPSEvents[0],g_hGPSEvents[1],NULL,0);
	}
	return (gps_h != NULL);
}

Gps::GPSCOORD* Gps::getPosition()
{
	GPSCOORD* coord = new GPSCOORD; 
	coord->init();

	DWORD dwRes;
	BYTE gpsPositionRaw[376];
	GPS_POSITION *gps = (GPS_POSITION*)gpsPositionRaw;
	gps->dwVersion = GPS_VERSION_1;
	gps->dwSize = sizeof(gpsPositionRaw);
	dwRes = GPSGetPosition(gps_h, gps, 60000, 0);
	if (ERROR_SUCCESS == dwRes) {
		PCWSTR pszFormat=L"%s\0";
		wsprintf(coord->szMessage,pszFormat, "Get position succeeded");

		coord->latitude = gps->dblLatitude;
		coord->longitude = gps->dblLongitude;
		if (0 < coord->latitude && 0 < coord->longitude)
			coord->valid = true;
	} else {
		PCWSTR pszFormat=L"%s\0";
		wsprintf(coord->szMessage,pszFormat, "Get position failed");
	}

	return coord;
}
